<?php

namespace app\api\controller;
//导入基类
use app\common\model\Coupon;
use app\common\model\Shoporder;
use app\common\model\UserCoupon as user_couponModel;
use app\common\model\User;
use think\Controller;
use think\facade\Cache;
use think\Db;
use app\common\model\Banner;
use app\common\model\FightTeam;
use app\common\model\Goods as goodsModel;
use think\Request;
use Endroid\QrCode\QrCode;
use app\common\model\IntegralLog as integralLoglModel;
use app\common\model\WalletLog as walletLoglModel;
use app\common\model\GoodsCategory as GoodsCategoryModel;
class Goods extends Controller
{
    //商品列表
    public function goods_list(){
        $data = array('code'=>1,'msg'=>'数据异常');
        $max_cat_id = GoodsCategoryModel::where('is_show',1)->order('sort_order desc')->value('cat_id');
        $param = $this->request->param();
        $goods_name = $this->request->param('goods_name')?$this->request->param('goods_name'):'';
        $type =$this->request->param('cat_id')?$this->request->param('cat_id'):$max_cat_id;
        $count = GoodsCategoryModel::where(['cat_id'=>$type,'is_show'=>1])->count();
        if(!$count){
            return json($data);
        }
        $start = 0;
        $limit = 10;
        if (!empty($param['length']) && !empty($param['start'])) {
            $start = ($param['start'] - 1) * $param['length'];
            $limit = $param['length'];
        }
        if($goods_name){
            $goods_list = goodsModel::where('name', 'like','%'.$goods_name.'%')->order('sort DESC')->order('id DESC')->field('id,cat_id,name,fighting_price as price,poster,start_time,end_time,landmark')->limit($start, $limit)->select();
            foreach ($goods_list as $key => $value) {
                $cat_name = GoodsCategoryModel::where('cat_id', $value['cat_id'])->value('cat_name');
                $goods_list[$key]['cat_name'] = $cat_name;
                $goods_list[$key]['str_start_time'] = date('Y.m.d', $value['start_time']);
                $goods_list[$key]['str_end_time'] = date('Y.m.d', $value['end_time']);
                $goods_list[$key]['remaining_time'] =0;
            }
            $cat_name = '商品列表';
        }else{
            switch($type) {
                //拼团秒杀的商品
                case 11:
                    $goods_list = goodsModel::where('cat_id', $type)->order('sort DESC')->order('id DESC')->field('id,cat_id,name,fighting_price as price,poster,start_time,end_time,landmark')->limit($start, $limit)->select();
                    foreach ($goods_list as $key => $value) {
                        $cat_name = GoodsCategoryModel::where('cat_id', $value['cat_id'])->value('cat_name');
                        $goods_list[$key]['cat_name'] = $cat_name;
                        $goods_list[$key]['str_start_time'] = date('Y.m.d', $value['start_time']);
                        $goods_list[$key]['str_end_time'] = date('Y.m.d', $value['end_time']);
                        $goods_list[$key]['remaining_time'] = 0;
                    }
                    $cat_name = $cat_name;
                    break;
                //限时秒杀的商品
                case 12:
                    $goods_list = goodsModel::where('cat_id', $type)->order('sort DESC')->order('id DESC')->field('id,cat_id,name,price_spike as price,poster,start_time,end_time,landmark')->limit($start, $limit)->select();
                    foreach ($goods_list as $key => $value) {
                        $cat_name = GoodsCategoryModel::where('cat_id', $value['cat_id'])->value('cat_name');
                        $goods_list[$key]['cat_name'] = $cat_name;
                        $goods_list[$key]['str_start_time'] = date('Y.m.d', $value['start_time']);
                        $goods_list[$key]['str_end_time'] = date('Y.m.d', $value['end_time']);
                        $goods_list[$key]['remaining_time'] = $value['end_time'] - time();

                    }
                    $cat_name = $cat_name;
                    break;
                default:
                    $goods_list = goodsModel::where('cat_id', $type)->order('sort DESC')->order('id DESC')->field('id,cat_id,name,sale_price as price,poster,start_time,end_time,landmark')->limit($start, $limit)->select();
                    foreach ($goods_list as $key => $value) {
                        $cat_name = GoodsCategoryModel::where('cat_id', $value['cat_id'])->value('cat_name');
                        $goods_list[$key]['cat_name'] = $cat_name;
                        $goods_list[$key]['str_start_time'] = date('Y.m.d', $value['start_time']);
                        $goods_list[$key]['str_end_time'] = date('Y.m.d', $value['end_time']);
                        $goods_list[$key]['remaining_time'] = 0;
                    }
                    $cat_name = $cat_name;
            }
        }
        $data = array('code'=>0,'msg'=>'获取成功','info'=>$goods_list,'cat_name'=> $cat_name);
        return  json($data);
    }
    public function goods_info(){
        $data = array('code'=>1,'msg'=>'数据异常');
        if(!session('userid') && !session('openid')){
            $parent_id = empty($_REQUEST['parent_id'])?'':$_REQUEST['parent_id'];
            return redirect('/api/login/login?parent_id='.$parent_id);
        }
        $goods_id = empty($_REQUEST['goods_id'])?'':$_REQUEST['goods_id'];
        $goods_info = goodsModel::where('id',$goods_id)->field('id,cat_id,name,sale_price,fighting_price,price_spike,img1,start_time,end_time,landmark,is_on,detail')->find();
        if(!$goods_id || empty($goods_info)){
            return json($data);
        }
        if($goods_info['cat_id'] == 11){
            header("location:".$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].'/api/goods/fight_goods_detail?goods_id='.$goods_id);
        }
        goodsModel::where('id',$goods_id)->setInc('pageviews',1);
        $cat_name = GoodsCategoryModel::where('cat_id', $goods_info['cat_id'])->value('cat_name');
        $img = explode(',',$goods_info['img1']);
        $info = [
            'id'=>$goods_info['id'],
            'cat_id'=>$goods_info['cat_id'],
            'name'=>$goods_info['name'],
            'landmark'=>$goods_info['landmark'],
            'detail'=>$goods_info['detail'],
            'cat_name'=>$cat_name,
            'img'=>$img,
            'str_start_time'=>date('Y.m.d', $goods_info['start_time']),
            'str_end_time'=>date('Y.m.d', $goods_info['end_time']),
            'is_on'=>$goods_info['is_on'],
        ];
        switch($goods_info['cat_id']){
            //拼团秒杀的商品
            case 11:
               $info['price']= $goods_info['fighting_price'];
               $info['remaining_time']= 0;
                break;
            //限时秒杀的商品
            case 12:
                $info['price']= $goods_info['price_spike'];
                $info['remaining_time']=  $goods_info['end_time'] - time();
                break;
            default:
                $info['price']= $goods_info['sale_price'];
                $info['remaining_time']= 0;
                break;
        }
        $order_info = Shoporder::alias('s')->join('langjin_user u','s.userid=u.id')->where('s.goods_id',$goods_id)->field('u.nickname,s.create_time')->select();
        $data = array('code'=>0,'msg'=>'获取成功','info'=>$info,'order_info'=>$order_info);
        return  json($data);
    }
    /**

     * 制作二维码图片

     * @return [type] [description]

     */

    public function qrcode($url,$dst_path)
    {
        $dst_path = ltrim($dst_path,'/');
        $dst_path = str_replace("\\","/",$dst_path);
        //加载第三方类库
        //vendor('/phpqrcode.phpqrcode');
        require_once "../vendor/phpqrcode/phpqrcode.php";
        //$url = "http://finance.china.com.cn/hz/gn/2345/20171127/19523.shtml";

        $size = 4;    //图片大小

        $errorCorrectionLevel = "Q"; // 容错级别：L、M、Q、H

        $matrixPointSize = "8"; // 点的大小：1到10
        //实例化
        $qr = new \QRcode();
        //会清除缓冲区的内容，并将缓冲区关闭，但不会输出内容。
        ob_end_clean();
        //输入二维码
        $errorCorrectionLevel = 'H';
        //设置生成二维码图片的大小
        $matrixPointSize = 3;
        //设置生成二维码的图片名称
        $filename = "uploads/haibao/".time().session('userid').rand(1000,10000).'.png';
         $qr::png($url, $filename, $errorCorrectionLevel, $matrixPointSize, 1);
        //var_dump($qr::png($url, $filename, $errorCorrectionLevel, $matrixPointSize, 1));exit;
        //————————————————————————————————————————————————————————————————
        //二维码上添加logo
        //$QR = $filename;
        //——————————————————————————————————————————
        // 加了logo的二维码放在海报之类的背景图上面
        //$dst_path = './img/xuexi.jpg';     //底图
        $src_path = $filename;     //覆盖图，我们就继续用上面的那张图QRlogo
        //创建图片实例
        $dst = imagecreatefromstring(file_get_contents($dst_path));
        $src = imagecreatefromstring(file_get_contents($src_path));
        //获取覆盖图的宽高
        list($src_w, $src_h) = getimagesize($src_path);
        list($src_w1, $src_h1) = getimagesize($dst_path);
        /**
         *
         * PHP函数：imagecopymerge()/imagecopy()
         *
         * bool imagecopymerge ( resource $dst_im , resource $src_im , int $dst_x , int $dst_y , int $src_x , int $src_y , int $src_w , int $src_h , int $pct )
         * 将 src_im 图像中坐标从 src_x，src_y 开始，宽度为 src_w，高度为 src_h 的一部分拷贝到 dst_im 图像中坐标为 dst_x 和 dst_y 的位置上。两图像将根据 pct 来决定合并程度，其值范围从 0 到 100。当 pct = 0 时，实际上什么也没做，当为 100 时对于调色板图像本函数和 imagecopy() 完全一样，它对真彩色图像实现了 alpha 透明。
         *
         */
        imagecopymerge($dst, $src, $src_w1-$src_w, $src_h1-$src_h, 0, 0, $src_w, $src_h, 100);
        $image = "uploads/haibao/".time().session('userid').rand(100,100000).'.png';
        imagepng($dst,$image);
        unlink($filename);
        imagedestroy($dst);
        imagedestroy($src);
        return $image;
    }
    //分享页面
    public function share(){
        $data = array('code'=>1,'msg'=>'数据异常');
        $goods_id =$this->request->param('goods_id')?$this->request->param('goods_id'):'';
        $info = goodsModel::where('id',$goods_id)->field('poster')->find();
        if($info){
            //获取当前用户ID
            $id = session('userid');
            //session('parent_id',$id);
            // $qrCode = new QrCode('mobile/index/index?id='.$id);//二维码地址
            $url=$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].'/api/goods/goods_info?parent_id='.$id.'&goods_id='.$goods_id;
            $img = $this->qrcode($url,$info['poster']);
            $data = array('code'=>0,'msg'=>'获取成功','img'=>$img);
            return  json($data);
        }
    }
    //商城分享
    public function shop_share(){
        $data = array('code'=>1,'msg'=>'数据异常');
        $id = session('userid');
        $info = User::where('id',$id)->value('share_img');
        if($info){
            //如果二维码存在的话直接返回
            $data = array('code'=>0,'msg'=>'获取成功','img'=>$info);
            return json($data);
        }else{
            //如果二维码不存在的话就创建并返回
            $url=$_SERVER['REQUEST_SCHEME'].'://'.$_SERVER['SERVER_NAME'].'/api/login/login?parent_id='.$id;
            $img = $this->share_qrcode($url);
            $res = User::where('id',$id)->update(['share_img'=>$img]);
            if($res){
                $data = array('code'=>0,'msg'=>'获取成功','img'=>$img);
            }
        }
        return json($data);
    }
    /**

     * 制作二维码图片

     * @return [type] [description]

     */

    public function share_qrcode($url)
    {

        require_once "../vendor/phpqrcode/phpqrcode.php";

        $size = 4;    //图片大小

        $errorCorrectionLevel = "Q"; // 容错级别：L、M、Q、H

        $matrixPointSize = "8"; // 点的大小：1到10
        //实例化
        $qr = new \QRcode();
        //会清除缓冲区的内容，并将缓冲区关闭，但不会输出内容。
        ob_end_clean();
        //输入二维码
        $errorCorrectionLevel = 'H';
        //设置生成二维码图片的大小
        $matrixPointSize = 3;
        //设置生成二维码的图片名称
        $dir = "uploads/qrcode/";
        if(!is_dir($dir)){
            mkdir($dir,0777);
        }
        $filename = $dir.time().session('userid').rand(1000,10000).'.png';
        $qr::png($url, $filename, $errorCorrectionLevel, $matrixPointSize, 1);

        return $filename;
    }
    //拼团商品详情（单独写）
    public function fight_goods_detail(){
        $data = array('code'=>1,'msg'=>'数据异常');
        if(!session('userid') && !session('openid')){
            $parent_id = empty($_REQUEST['parent_id'])?'':$_REQUEST['parent_id'];
            return redirect('/api/login/login?parent_id='.$parent_id);
        }
        $goods_id = empty($_REQUEST['goods_id'])?'':$_REQUEST['goods_id'];
        $goods_info = goodsModel::where('id',$goods_id)->field('id,cat_id,name,sale_price,fighting_price,img1,start_time,end_time,landmark,is_on,detail,people_count')->find();
        if(!$goods_id || empty($goods_info || $goods_info['cat_id'] != 11)){
            return json($data);
        }
        goodsModel::where('id',$goods_id)->setInc('pageviews',1);
        $cat_name = GoodsCategoryModel::where('cat_id', $goods_info['cat_id'])->value('cat_name');
        $img = explode(',',$goods_info['img1']);
        $info = [
            'id'=>$goods_info['id'],
            'cat_id'=>$goods_info['cat_id'],
            'sale_price'=>$goods_info['sale_price'],
            'fighting_price'=>$goods_info['fighting_price'],
            'name'=>$goods_info['name'],
            'landmark'=>$goods_info['landmark'],
            'detail'=>$goods_info['detail'],
            'cat_name'=>$cat_name,
            'img'=>$img,
            'is_on'=>$goods_info['is_on'],
        ];
        //获取当前拼团团队数量
        $fight_info = FightTeam::alias('f')->join('langjin_user u','f.userid = u.id')->where(['f.goods_id'=>$goods_id,'f.status'=>0])->order('id desc')->limit(5)->field('f.*,u.nickname,u.head_img')->select();
        foreach($fight_info as $key=>$value){
            $fight_count = Shoporder::where('fight_id',$value['id'])->where('status',1)->count();
            $lack_count = $goods_info['people_count'] - $fight_count;
            $value['lack_count'] = $lack_count;
            $value['expired_time'] = date('Y-m-d H:i:s',$value['expired_time']);
            $result[]= $value;
        }
        $data = array('code'=>0,'msg'=>'获取成功','info'=>$info,'fight_info'=>$result);
        return  json($data);
    }
    //拼团购买
    public function fight_buy(){
        if(request()->isPost()) {
            $goods_id = $this->request->param('goods_id');
            $coupon_id = $this->request->param('coupon_id') ? $this->request->param('coupon_id') : 0;
            $fight_id = $this->request->param('fight_id') ? $this->request->param('fight_id') : 0;
            $goods_info = goodsModel::where('id', $goods_id)->find();
            $type = $this->request->param('type') ? $this->request->param('type') : 0;//0 发起拼团 1加入拼团 2单独购买
            $userid = session('userid');
            $openId = session('openid');
            if (empty($goods_info)) {
                $data = [
                    'code' => 1, 'msg' => '商品不存在',
                ];
                return json($data);
            }
            if ($goods_info['cat_id'] != 11) {
                $data = [
                    'code' => 1, 'msg' => '该商品不是拼团商品',
                ];
                return json($data);
            }
       // print_r($goods_info);exit;
            if ($goods_info['amount'] <= 0  || $goods_info['is_on'] == '否') {
                $data = [
                    'code' => 1, 'msg' => '商品已售罄',
                ];
                return json($data);
            }
            // 启动事务
            Db::startTrans();
            try {
                switch ($type) {
                    //如果是发起拼团，创建拼团表
                    case 0:
                        $data = [
                            'goods_id' => $goods_id,
                            'userid' => $userid,
                            'status' => 0,
                            'expired_time' => time() + $goods_info['fight_time'],
                        ];
                        $fight_id = FightTeam::insertGetId($data);
                        if ($fight_id) {
                            $price = (float)$goods_info['fighting_price'];
                        }
                        break;
                    //如果是加入拼团
                    case 1:
                        $info = FightTeam::where(['id' => $fight_id, 'status' => 0, 'goods_id' => $goods_id])->find();
                        //看已经加入该拼团的人数
                        if ($info && $info['status'] == 0) {
                            $fight_count = Shoporder::where('fight_id', $fight_id)->where('status','in','0,1')->count();
                            if ($fight_count == $goods_info['people_count']) {
                                //如果该团已经满了 ，就改变状态
                                FightTeam::where('id', $fight_id)->update(['status' => 1]);
                            }
                            if ($fight_count >= $goods_info['people_count']) {
                                $data = [
                                    'code' => 1, 'msg' => '该拼团已满',
                                ];
                                return json($data);
                            }
                            if($info['userid'] == $userid){
                                $data = [
                                    'code' => 1, 'msg' => '不能参加自己的拼团哦',
                                ];
                                return json($data);
                            }
                        } else {
                            $data = [
                                'code' => 1, 'msg' => '该拼团不存在',
                            ];
                            return json($data);
                        }
                        $price = (float)$goods_info['fighting_price'];
                        break;
                    //如果是单独购买的话
                    case 2:
                        $price = (float)$goods_info['sale_price'];
                    default:
                        break;
                }
                //判断优惠券是否可以用
                $coupon_info = user_couponModel::alias('u')->join('langjin_coupon c', 'c.id = u.coupon_id')->where('u.id', $coupon_id)->where('u.userid', $userid)->where('c.expired_time', '<', time())->field('u.coupon_id,u.status,c.full_amount,c.amount')->find();
                if ($coupon_info && $coupon_id) {
                    if($coupon_info['status']!=0){
                        $data = [
                            'code' => 1, 'msg' => '优惠券已使用',
                        ];
                        return json($data);
                    }
                    $coupon_cat = Coupon::where('id', $coupon_info['coupon_id'])->find();
                        if($coupon_cat['status'] == 1){
                            $data = [
                                'code' => 1, 'msg' => '优惠券不可用',
                            ];
                            return json($data);
                        }
                        if ($coupon_cat['cat_id'] == 2) {
                            //如果是满减优惠券的话看能不能用
                            if (bccomp($price, $coupon_cat['full_amount'], 2) < 0) {
                                $data = [
                                    'code' => 1, 'msg' => '优惠券不可用',
                                ];
                                return json($data);
                            }
                            $price = $price - $coupon_cat['amount'];
                        } else {
                            if (bccomp($price, $coupon_cat['amount'], 2) < 0) {
                                $data = [
                                    'code' => 1, 'msg' => '优惠券不可用',
                                ];
                                return json($data);
                            }
                            $price = $price - $coupon_cat['amount'];
                        }
                } else {
                    $coupon_id = 0;
                }
                Db::commit();
            } catch (\Exception $e) {
                // 回滚事务
                Db::rollback();
            }
                $order_number = $this->make_order($goods_id, $price, $coupon_id);
                if (!$order_number) {
                    $data = [
                        'code' => 1, 'msg' => '数据异常',
                    ];
                    return json($data);
                }
                if ($type == 1 || $type == 0) {
                    Shoporder::where('order_number',$order_number)->update(['fight_id' => $fight_id]);
                }
                require_once "wxpay/lib/WxPay.Api.php";
                require_once "wxpay/example/WxPay.Config.php";
                require_once "wxpay/example/WxPay.JsApiPay.php";
                $tools = new \JsApiPay();
                //②、统一下单
                $input = new \WxPayUnifiedOrder();
                $input->SetBody("pay");
                $input->SetAttach("test");
                $input->SetOut_trade_no($order_number);//订单号
                $input->SetTotal_fee($price * 100);
                $input->SetTime_start(date("YmdHis"));
                $input->SetTime_expire(date("YmdHis", time() + 600));
                $input->SetGoods_tag("test");
                $input->SetNotify_url($_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['SERVER_NAME'] . "/api/login/response");
                $input->SetTrade_type("JSAPI");
                $input->SetOpenid($openId);
                $config = new \WxPayConfig();
                $order = \WxPayApi::unifiedOrder($config, $input);
                //echo '<font color="#f00"><b>统一下单支付单信息</b></font><br/>';
                //printf_info($order);
                $jsApiParameters = $tools->GetJsApiParameters($order);
                $data = [
                    'code' => 0, 'msg' => '获取成功', 'info' => $jsApiParameters
                ];
                return json($data);
                // 提交事务
        }else{
            $data = [
                'code' => 1, 'msg' => '数据异常',
            ];
            return json($data);
        }

    }
    //创建订单
    public function make_order($goods_id,$price,$coupon_id){
        $data['order_number'] = $this->createordernum();
        $data['userid'] = session('userid');
        $data['goods_id'] = $goods_id;
        $data['num'] = 1;
        $data['poundage'] = 0;
        $data['tprice'] = $price;
        $data['status'] = 0;
        $data['coupon_id'] = $coupon_id;
        $res = Shoporder::create($data);
        if($res){
            goodsModel::where('id',$goods_id)->setDec('amount',1);
            return $data['order_number'];
        }else{
            return false;
        }
    }
    //生成唯一订单号
    public function createordernum()
    {
        $order_number=mt_rand(100000,999999).substr(microtime(), 2, 5).date('YmdHis');
        //判断是否已存在
        $result=Shoporder::where('order_number',$order_number)->find();
        if(!$result){
            return $order_number;
        }else{

            return $this->createordernum();
        }
    }
    //提交订单页面
    public function sub_order(){
        $goods_id = $this->request->param('goods_id');
        $userid= session('userid');
        $type= $this->request->param('type')?$this->request->param('type'):0;
        $goods_info = goodsModel::where('id',$goods_id)->find();
        if(empty($goods_info)){
            $data = [
                'code' => 1, 'msg' => '商品不存在',
            ];
            return json($data);
        }
        switch($goods_info['cat_id']){
            //如果是拼团商品
            case 11:
                if($type){
                    //如果是发起拼团或者是拼单
                    $price = $goods_info['fighting_price'];
                }else{
                    $price = $goods_info['sale_price'];
                }
            break;
            //如果是秒杀商品
            case 12:
                $price = $goods_info['price_spike'];
                break;
            default:
                $price = $goods_info['sale_price'];

        }
        $goods_res = [
            'img' =>$goods_info['poster'],
            'name' =>$goods_info['name'],
            'price' =>$price,
        ];
        user_couponModel::alias('u')->join('langjin_coupon c','c.id = u.coupon_id')->where('u.userid',$userid)->where('c.expired_time','<',time())->update(['u.status'=>2]);
        //当前用户的优惠券列表
        $coupon_list = user_couponModel::alias('u')->join('langjin_coupon c','u.coupon_id = c.id')->where(['userid'=>$userid,'u.status'=>0])->where('c.status',0)->field('u.id,c.cat_id,c.amount,c.full_amount')->select();
        $count = user_couponModel::alias('u')->join('langjin_coupon c','u.coupon_id = c.id')->where(['userid'=>$userid,'u.status'=>0])->where('c.status',0)->count();
        $res = array();
        foreach($coupon_list as $key=>$value){
            $res['id'] = $value['id'];
            if($value['cat_id'] == 2){
                //如果是满减优惠券
                $res['content'] = '满'.$value['full_amount'].'减'.$value['amount'];
            }else{
                $res['content'] = '立减'.$value['amount'];
            }
            $info[] = $res;
        }
        $data = [
            'code' => 0, 'msg' => '获取成功','goods_info'=>$goods_res,'info'=>$info,'count'=>$count
        ];
        return json($data);
    }

}